package router

import (
	"context"
	"github.com/google/wire"
	"net/http"
	"os"
	"path/filepath"
	"sieve_admin_server_userpass/app/api"
	"sieve_admin_server_userpass/app/api/amazon_sieve"
	"sieve_admin_server_userpass/app/api/customer"
	"sieve_admin_server_userpass/app/api/fb_sieve"
	"sieve_admin_server_userpass/app/api/ins_sieve"
	"sieve_admin_server_userpass/app/api/linkedin_sieve"
	"sieve_admin_server_userpass/app/api/logger"
	"sieve_admin_server_userpass/app/api/number"
	"sieve_admin_server_userpass/app/api/sieve"
	"sieve_admin_server_userpass/app/api/sys"
	"sieve_admin_server_userpass/app/api/util"
	"sieve_admin_server_userpass/app/api/viber_sieve"
	"sieve_admin_server_userpass/app/api/ws_sieve"
	"sieve_admin_server_userpass/app/server"
	serviceUtil "sieve_admin_server_userpass/app/service/util"
	"sieve_admin_server_userpass/lib/config"
	"strings"
)

var (
	_ IRouter = (*Router)(nil)

	RouterSet = wire.NewSet(wire.Struct(new(Router), "*"), wire.Bind(new(IRouter), new(*Router)))

	sieveClient = *config.String("sieve.user.server", "sieve_admin_server_userpass", "file storage dir prefix")
)

type IRouter interface {
	RegisterAPI()
}

type Router struct {
	ResourceAPI            *api.ResourceAPI
	NoticeAPI              *sys.NoticeAPI
	CountryAPI             *sys.CountryAPI
	RoleAPI                *sys.RoleAPI
	MenuAPI                *sys.MenuAPI
	UserAPI                *customer.UserAPI
	UserAuthAPI            *customer.UserAuthAPI
	InComeAPI              *customer.InComeAPI
	BusinessTypeAPI        *customer.BusinessTypeAPI
	BusinessPriceAPI       *customer.BusinessPriceAPI
	DailyRechargeAPI       *customer.DailyRechargeAPI
	AnnouncementAPI        *customer.AnnouncementAPI
	RechargeAPI            *customer.RechargeAPI
	UserRecordsAPI         *customer.UserRecordsAPI
	SieveConfigAPI         *customer.SieveConfigAPI
	CustomizedAPI          *number.CustomizedAPI
	SelectedAPI            *number.SelectedAPI
	NumberSegmentAPI       *number.NumberSegmentAPI
	TaskListAPI            *number.TaskListAPI
	LoginAPI               *logger.LoginAPI
	BusinessAPI            *logger.BusinessAPI
	WsUploadSieveAPI       *ws_sieve.UploadSieveAPI
	WsActiveAPI            *ws_sieve.SieveActiveAPI
	WsSieveValidAPI        *ws_sieve.SieveValidAPI
	WsSieveSexAPI          *ws_sieve.SieveSexAPI
	FbUploadSieveAPI       *fb_sieve.UploadSieveAPI
	FbSieveValidAPI        *fb_sieve.SieveValidAPI
	InsUploadSieveAPI      *ins_sieve.UploadSieveAPI
	InsSieveValidAPI       *ins_sieve.SieveValidAPI
	LinkedinUploadSieveAPI *linkedin_sieve.UploadSieveAPI
	LinkedinSieveValidAPI  *linkedin_sieve.SieveValidAPI
	AmazonUploadSieveAPI   *amazon_sieve.UploadSieveAPI
	AmazonSieveValidAPI    *amazon_sieve.SieveValidAPI
	ViberUploadSieveAPI    *viber_sieve.UploadSieveAPI
	SieveTaskListAPI       *sieve.TaskListAPI
	EngineAPI              *sieve.EngineAPI
}

//
// var (
//	treeParentMap = map[string]*server.BatchModTree{
//		"sys": {
//			Name:  "sys",
//			Title: "系统管理",
//			Order: 2700,
//			Icon:  "ios-git-network",
//		},
//		"customer": {
//			Name:  "customer",
//			Title: "客户管理",
//			Order: 2600,
//			Icon:  "ios-contact-outline",
//		},
//		"number": {
//			Name:  "number",
//			Title: "号码管理",
//			Order: 2500,
//			Icon:  "ios-call-outline",
//		},
//		"log": {
//			Name:  "log",
//			Title: "日志管理",
//			Order: 2400,
//			Icon:  "ios-paper-outline",
//		},
//	}
// )
//
// func (a *Router) RegisterAPI() {
//	var (
//		modTreeMap = map[string][]util.API{
//			"sys": {
//				a.CountryAPI,
//				a.RoleAPI,
//				a.NoticeAPI,
//				a.MenuAPI,
//			},
//			"customer": {
//				a.UserAPI,
//				a.UserAuthAPI,
//				a.InComeAPI,
//				a.BusinessTypeAPI,
//				a.AnnouncementAPI,
//				a.RechargeAPI,
//				a.DailyRechargeAPI,
//				a.UserRecordsAPI,
//			},
//			"log": {
//				a.LoginAPI,
//				a.BusinessAPI,
//			},
//		}
//	)
//
//	var sysMenu []*server.BatchModTree
//	for k, v := range treeParentMap {
//		var (
//			batchModTree = v
//		)
//		for _, vv := range modTreeMap[k] {
//			go vv.Cron()
//			batchModTree.Children = append(batchModTree.Children, vv.GetApis()...)
//		}
//
//		sysMenu = append(sysMenu, batchModTree)
//		server.BatchRegModTree(batchModTree)
//	}
//
//	a.MenuAPI.AddMenus(context.Background(), sysMenu)
//
//	http.HandleFunc("/storage/", func(w http.ResponseWriter, r *http.Request) {
//		w.Header().Set("Access-Control-Allow-Origin", "*")
//
//		http.ServeFile(w, r, filepath.Join(serviceUtil.GetSieveFilePath(serviceUtil.FileStorage), r.URL.Path[len("/storage/"):]))
//	})
// }

var (
	treeParentMap = map[string]*server.BatchModTree{
		"sys": {
			Name:  "sys",
			Title: "系统管理",
			Order: 2700,
			Icon:  "ios-git-network",
		},
		"customer": {
			Name:  "customer",
			Title: "客户管理",
			Order: 2600,
			Icon:  "ios-contact-outline",
		},
		"number": {
			Name:  "number",
			Title: "号码管理",
			Order: 2500,
			Icon:  "ios-call-outline",
		},
		"log": {
			Name:  "log",
			Title: "日志管理",
			Order: 2400,
			Icon:  "ios-paper-outline",
		},
		"sieve": {
			Name:  "sieve",
			Title: "筛选管理",
			Order: 2300,
			Icon:  "ios-tablet-portrait",
		},
	}
)

func (a *Router) RegisterAPI() {
	var (
		modTreeMap = map[string][]util.API{
			"sys": {
				a.CountryAPI,
				a.RoleAPI,
				// a.NoticeAPI,
				a.MenuAPI,
			},
			"customer": {
				a.UserAPI,
				a.UserAuthAPI,
				a.InComeAPI,
				a.BusinessTypeAPI,
				a.BusinessPriceAPI,
				// a.AnnouncementAPI,
				a.RechargeAPI,
				a.DailyRechargeAPI,
				a.UserRecordsAPI,
				a.SieveConfigAPI,
			},
			"number": {
				a.CustomizedAPI,
				a.SelectedAPI,
				a.NumberSegmentAPI,
				a.TaskListAPI,
			},
			"log": {
				a.LoginAPI,
				a.BusinessAPI,
			},
			"wsSieve": {
				a.WsUploadSieveAPI,
				a.WsActiveAPI,
				a.WsSieveValidAPI,
				a.WsSieveSexAPI,
			},
			"sieve": {
				a.SieveTaskListAPI,
				a.EngineAPI,
			},
		}
	)

	var sysMenu []*server.BatchModTree
	for k, v := range treeParentMap {
		var (
			batchModTree = v
		)
		for _, vv := range modTreeMap[k] {
			go vv.Cron()
			batchModTree.Children = append(batchModTree.Children, vv.GetApis()...)
		}

		sysMenu = append(sysMenu, batchModTree)
		server.BatchRegModTree(batchModTree)
	}

	a.MenuAPI.AddMenus(context.Background(), sysMenu)

	http.HandleFunc("/storage/", func(w http.ResponseWriter, r *http.Request) {
		w.Header().Set("Access-Control-Allow-Origin", "*")
		var bizTyMap = map[string]int{
			"ws":          1,
			"fb":          2,
			"ins":         3,
			"amazon":      4,
			"linkedin":    5,
			"viber":       6,
			"line":        7,
			"zalo":        8,
			"twitter":     9,
			"skype":       10,
			"tg":          11,
			"momo":        12,
			"mtn_momo":    13,
			"microsoft":   14,
			"true_money":  15,
			"botim":       16,
			"operator":    17,
			"phone_check": 18,
			"tk":          19,
		}
		var s = map[string]struct{}{
			"sieve":  {},
			"upload": {},
			"dedupe": {},
		}
		p := r.URL.Path[len("/storage/"):]
		ss := strings.Split(p, "/")
		sieveUserBase := *config.String("sieve_admin_server_userpass.exec_name", "sieve_admin_server_userpass", "file storage dir prefix")
		sieveUserDir := *config.String("sieve_admin_server_userpass.exec_path", "/data/sieve_admin_server_userpass", "file storage dir prefix")
		pp := filepath.Join(serviceUtil.GetFilePath(serviceUtil.FileStorage(sieveUserBase), false, sieveUserDir), p)
		if len(ss) > 2 {
			// 判断是否是下载筛料文件，如果是的，从客户端的文件地址下载
			if _, ok := bizTyMap[ss[0]]; ok {
				if _, ok := s[ss[1]]; ok {
					execName := strings.Split(os.Args[0], ".")[0]
					pp = strings.Replace(pp, execName, sieveClient, -1)
				}
			} else {
				pp = filepath.Join(serviceUtil.GetFilePath(serviceUtil.FileStorage()), r.URL.Path[len("/storage/"):])
			}
		}
		http.ServeFile(w, r, pp)
	})
}
